package com.example.shardingsphere.rule;

import com.google.common.collect.Lists;
import org.apache.shardingsphere.sharding.api.sharding.standard.PreciseShardingValue;
import org.apache.shardingsphere.sharding.api.sharding.standard.RangeShardingValue;
import org.apache.shardingsphere.sharding.api.sharding.standard.StandardShardingAlgorithm;
import org.joda.time.DateTime;

import java.util.Collection;
import java.util.Date;
import java.util.List;

public class CustomTableCreateDateRule implements StandardShardingAlgorithm<Date> {

    @Override
    public String doSharding(Collection<String> collection, PreciseShardingValue<Date> preciseShardingValue) {
        return null;
    }

    @Override
    public Collection<String> doSharding(Collection<String> collection, RangeShardingValue<Date> rangeShardingValue) {
        // 最小临界值
        Date minDate = rangeShardingValue.getValueRange().lowerEndpoint();
        // 最大临界值
        Date maxDate = rangeShardingValue.getValueRange().upperEndpoint();
        // 逻辑表
        String logicTable = rangeShardingValue.getLogicTableName();

        List<String> newTableList = Lists.newArrayList();
        if (null != minDate && null != maxDate) {
            DateTime startTime = new DateTime(minDate);
            while (startTime.compareTo(new DateTime(maxDate)) <= 0) {
                String temp = startTime.toString("yyyy_M");
                newTableList.add(logicTable + "_" + temp);
                startTime = startTime.plusMonths(1);
            }
        }

        return newTableList;
    }

    @Override
    public void init() {

    }

    @Override
    public String getType() {
        return null;
    }
}
